package com.dzm.xgb.sms.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.dzm.common.constants.RedisConstants;
import com.dzm.xgb.sms.properties.SmsProperties;
import com.dzm.xgb.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 作者：Dzm
 * 时间：2024-08-29-11:31
 * 功能：
 */

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    //发送短信验证码
    @Override
    public String sendMsg(String phoneNumber) throws Exception {
        //创建发送请求的客户端对象
        Config config = new Config()
                .setAccessKeyId(SmsProperties.ACCESS_KEY)
                .setAccessKeySecret(SmsProperties.ACCESS_SECRET)
                .setEndpoint(SmsProperties.ENDPOINT);

        Client client = new Client(config);

        //生成验证码
        String code = RandomUtil.randomNumbers(6);
        Map<String, String> map = new HashMap<>();
        map.put("code", code);

        //发送短信
        //构造请求对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phoneNumber)
                .setSignName(SmsProperties.SIGN_NAME)
                .setTemplateCode(SmsProperties.TEMPLATE_CODE)
                .setTemplateParam(JSONUtil.toJsonStr(map));

        //获取响应对象
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);

        //将验证码存入缓存
        redisTemplate.opsForValue().set(RedisConstants.PHONE_CODE + phoneNumber, code, 30, TimeUnit.DAYS);

        System.out.println(JSONUtil.toJsonStr(sendSmsResponse));
        return code;
    }


}
